package com.ali.gts.servlet.controller;

import com.ali.gts.servlet.domain.User;
import com.ali.gts.servlet.service.UserService;
import com.ali.gts.servlet.service.impl.UserServiceImpl;
import com.ali.gts.servlet.util.WebUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;

public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    Map<String, Function<String,Method>> map = new HashMap<>();

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        System.out.println("UserServlet 初始化中");

       String login =  servletConfig.getInitParameter("login");
       String register = servletConfig.getInitParameter("register");
       String logout = servletConfig.getInitParameter("logout");
       String ajaxExistsUsername = servletConfig.getInitParameter("ajaxExistsUsername");

       map.put(login,(login1)->{
           try {
               return this.getClass().getDeclaredMethod(login1,HttpServletRequest.class,HttpServletResponse.class);
           } catch (NoSuchMethodException e) {
              return null;
           }
       });

       map.put(register,(register1)->{
           try {
               return this.getClass().getDeclaredMethod(register1,HttpServletRequest.class,HttpServletResponse.class);
           } catch (NoSuchMethodException e) {
               return null;
           }
       });

        map.put(logout,(logout1)->{
            try {
                return this.getClass().getDeclaredMethod(logout1,HttpServletRequest.class,HttpServletResponse.class);
            } catch (NoSuchMethodException e) {
                return null;
            }
        });

        map.put(ajaxExistsUsername,(logout1)->{
            try {
                return this.getClass().getDeclaredMethod(logout1,HttpServletRequest.class,HttpServletResponse.class);
            } catch (NoSuchMethodException e) {
                return null;
            }
        });


    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            System.out.println("通过函数来进行优化");
            map.get(action).apply(action).invoke(this,request,response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
//        try {
//            //返回指定名称和参数的该类的方法，此方法返回的Method对象
//            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
//            //方法的调用
//            method.invoke(this,request,response);
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }




//        if("login".equals(action)){
//           this.login(request,response);
//        }else{
//            System.out.println("处理注册的需求");
//            this.register(request,response);
//        }





    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求参数数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2. 调用userService对象的login方法处理  -->返回一个boolean结果
        User loginUser = userService.login(username, password);
        //boolean success = true;
        //3. 根据boolean结果转向到不同的页面
        if(loginUser != null) {
            request.getSession().setAttribute("username",username);
            request.getSession().setAttribute("user",loginUser);
            //重定向到login_success.html
            response.sendRedirect("/index.jsp");
        } else {
            //转发到login_error.html
            request.getRequestDispatcher("/client/user/login_error.jsp").forward(request, response);
        }


    }

    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求参数数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        //2.检查验证码是否正确 此时先写死验证码
        if("abcde".equalsIgnoreCase(code)){

            //3.检查用户名是否存在
            if(userService.existUsername(username)){
                System.out.println("用户名已经存在");
                //把错误信息放到session 中 来回显数据
                request.setAttribute("message","用户名已经存在");
                request.getRequestDispatcher("/client/user/regist.jsp").forward(request,response);
            }else {
                //用户信息放到数据库
                String id = UUID.randomUUID().toString();//生成一个36位的随机值作为id
                Map<String, String[]> map  = request.getParameterMap();
                User user = WebUtil.copyParamToBean(map,new User());
                user.setId(id);
                boolean success = userService.regist(user);
                request.getRequestDispatcher("/client/user/regist_success.jsp").forward(request, response);

            }

        }else{
            System.out.println("验证码不正确跳转到注册页面");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }

    //注销登陆
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置session过期
        request.getSession().invalidate();
        //重定向到首页或者登陆页面
        response.sendRedirect("/index.jsp");
    }


    //校验用户名是否已经存在
    protected  void ajaxExistsUsername(HttpServletRequest rep,HttpServletResponse req) throws ServletException, IOException{

    }


}
